/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.srgsxmldb.manager;

import cz.muni.fi.pb138.srgsxmldb.database.BaseXDBFactory;
import cz.muni.fi.pb138.srgsxmldb.fileUtils.FileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.fileupload.FileItem;
import org.basex.core.BaseXException;
import org.basex.core.Context;
import org.basex.core.cmd.Add;
import org.basex.core.cmd.Delete;
import org.basex.core.cmd.XQuery;

/**
 *
 * @author Eldred
 */
public class XManager implements IXManager{

    @Override
    public void addGrammarFromXMLFile(FileItem file) {
        
        if(file==null)
            throw new NullPointerException("file");        
        ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pb138.srgsxmldb.properties/baseXdatabase");        
 
        
        
        try {
            
            FileUtil.copy(file, new FileOutputStream(rb.getString("databaseAddress")+file.getName()));
            
        } catch (IOException ex) {
            Logger.getLogger(XManager.class.getName()).log(Level.SEVERE, null, ex);
        }
         


        try {
            
            Context context = new Context();
            
            BaseXDBFactory.openCollection(context); 
            new Delete(file.getName()).execute(context);
            new Add("", rb.getString("databaseAddress")+file.getName()).execute(context);
            BaseXDBFactory.closeCollection(context);   
            
            context.close();
            
        } catch (BaseXException ex) {
            Logger.getLogger(XManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void deleteGrammarByFileName(String filename) {
        
        if(filename==null)
            throw new NullPointerException("filename");        
        ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pb138.srgsxmldb.properties/baseXdatabase"); 
         
            
        FileUtil.deleteFile(rb.getString("databaseAddress")+filename);
            
        try {
            
            Context context = new Context();
                
            BaseXDBFactory.openCollection(context); 
            new Delete(filename).execute(context);
            BaseXDBFactory.closeCollection(context);   

            context.close();
            
        } catch (BaseXException ex) {
            Logger.getLogger(XManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }  
    

    @Override
    public String[] getGrammarFileNameByRoot(String root) {
        
        if(root==null)
            throw new NullPointerException("root");
        ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pb138.srgsxmldb.properties/baseXdatabase");
        String raw = null;
            
        try {
            
            Context context = new Context();        
            BaseXDBFactory.openCollection(context);           
            raw = (new XQuery(
                "for $doc in collection('"+rb.getString("collectionName") +"')" +
                "where $doc//@root='"+ root +"'" +
                "return concat('',base-uri($doc))"
            ).execute(context));         
            BaseXDBFactory.closeCollection(context);        
            context.close();
            
        } catch (BaseXException ex) {
            Logger.getLogger(XManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        String[] lines;
        
        if (raw.isEmpty())
            return null;
        
        lines = raw.split("\\s");
    
        for(int i = 0; i<lines.length; i++) {

            lines[i] = (FileUtil.extractFileName(lines[i]));        
        }
        
        if (lines.length==0 || lines == null) {
            
            throw new IllegalStateException("ziaden file name");      
        }
        
        return lines;       
    }

    @Override
    public String getGrammarRootByFileName(String filename) {
        
        if(filename==null)
            throw new NullPointerException("root");
        ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pb138.srgsxmldb.properties/baseXdatabase");
        String result = null;
        
        try {
            
            Context context = new Context();        
            BaseXDBFactory.openCollection(context);           
            result = (new XQuery(
                        "for $doc in collection('"+rb.getString("collectionName") +"')" +
                        "let $file-path := base-uri($doc)" +
                        "where ends-with($file-path, '" + filename+"')" +
                        "return $doc//@root/string()"
                    ).execute(context));         
            BaseXDBFactory.closeCollection(context);        
            context.close();
            
        } catch (BaseXException ex) {
            Logger.getLogger(XManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (result.isEmpty() || result == null) {
            
            throw new IllegalStateException("ziaden root");      
        }
        
        return result;
    }

    @Override
    public String[] getAllGrammars() {
        
        ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pb138.srgsxmldb.properties/baseXdatabase");
        String raw = null;
            
        try {
            
            Context context = new Context();        
            BaseXDBFactory.openCollection(context);           
            raw = (new XQuery(
                "for $doc in collection('"+rb.getString("collectionName") +"')" +
                "return concat('',base-uri($doc))"
            ).execute(context));         
            BaseXDBFactory.closeCollection(context);        
            context.close();
            
        } catch (BaseXException ex) {
            Logger.getLogger(XManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        String lines[] = raw.split("\\s");
    
        for(int i = 0; i<lines.length; i++) {

            lines[i] = (FileUtil.extractFileName(lines[i]));        
        }
        
        if (lines.length==0 || lines == null) {
            
            throw new IllegalStateException("ziaden file name");      
        }
        
        return lines;  
    }

    @Override
    public File getGrammarFileByFileName(String filename) {
        
        if(filename==null)
            throw new NullPointerException("filename");        
        ResourceBundle rb = ResourceBundle.getBundle("cz.muni.fi.pb138.srgsxmldb.properties/baseXdatabase"); 
        
        File file = new File(rb.getString("databaseAddress")+filename);
        
        if (file == null)
            throw new NullPointerException("there is no such file");
        
        return file;
    }
    
}
